//
//  ST_EditMyVoiceSignCell.swift
//  btvideo
//
//  Created by Jason on 2022/2/24.
//  Copyright © 2022 JarvanZhang. All rights reserved.
//

import UIKit
//import Rswift
import RxCocoa
import RxSwift

class ST_EditMyVoiceSignCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        
        [playBtn,progress_view,total_seconds_label].forEach{ contentView.addSubview($0) }
        
        playBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.width.equalTo(32)
            make.height.equalTo(32)
        }
        
        total_seconds_label.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
        }
        
        progress_view.snp.makeConstraints { make in
            make.left.equalTo(playBtn.snp.right).offset(8)
            make.right.equalTo(total_seconds_label.snp.left).offset(-8)
            make.centerY.equalToSuperview()
            make.height.equalTo(3)
        }
        
    }
    
    
    fileprivate lazy var playBtn:UIButton = {
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.setImage(ST_ImageUtils.imageName("voice_sign_play_icon"), for: .normal)
        btn.setImage(ST_ImageUtils.imageName("voice_sign_play_icon_sel"), for: .selected)
        btn.addTarget(self, action: #selector(click_btn), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    fileprivate lazy var progress_view:UIProgressView = {
        let l = UIProgressView()
        l.progressViewStyle = .bar
        l.trackTintColor = UIColor(hex: 0xE8EAEE)
        l.progressTintColor = UIColor(hex: 0xFEC207)
        return l
    }()
    
    fileprivate lazy var total_seconds_label:UILabel = {
        let l = UILabel()
        l.textColor = .black
        l.text = "0s"
        l.font = .systemFont(ofSize: 11, weight: .regular)
        return l
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var player:AVPlayer?
    private var playerItem: AVPlayerItem?
    private var time_observer_token: Any?
    
    private lazy var audio_session: AVAudioSession = {
        let session = AVAudioSession.sharedInstance()
        return session
    }()
    
    /// 是否正在播放
    private var isPlaying = false{
        didSet{
            
            playBtn.isSelected = isPlaying
            
        }
    }
    
    
    var model:ST_EditMyVoiceSignCellModel_Copy?{
        didSet{
            
            
            stop_playing()
            guard let m = model else {
                return
            }
            
            total_seconds_label.text = m.duration.string + "s"
            progress_view.progress = 0
        }
    }
}

extension ST_EditMyVoiceSignCell{
    
    @objc func click_btn(){
        
        if isPlaying{
            stop_playing()
        }else{
            play()
        }
        
    }
    
    func stop_playing(){
        
        isPlaying = false
        progress_view.progress = 0
        
        remove_periodic_time_observer()
        NotificationCenter.default.removeObserver(self)
        
        player = nil
        playerItem = nil
        time_observer_token = nil
    }
    
    func play(){
        
        guard let m = model else {
            stop_playing()
            return
        }
        
        do {
            
            try self.audio_session.setCategory(.playback, mode: .default)
            try self.audio_session.setActive(true)
            
            let playerItem = AVPlayerItem(url: m.url)
            player = AVPlayer(playerItem:playerItem)
            self.playerItem = playerItem
            player?.rate = 1.0;
            player?.play()
            
            NotificationCenter.default.addObserver(self, selector: #selector(player_did_finish_playing(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
            
            isPlaying = true
            progress_view.progress = 0
            
            addPeriodicTimeObserver()
            
        } catch {
            print(error)
        }
        
    }
    
    @objc func player_did_finish_playing(note: NSNotification) {
        
        isPlaying = false
        progress_view.progress = 1
        
        
    }
    
    private func addPeriodicTimeObserver() {
        // Notify every half second
        let timeScale = CMTimeScale(NSEC_PER_SEC)
        let time = CMTime(seconds: 0.5, preferredTimescale: timeScale)
        
        time_observer_token = player?.addPeriodicTimeObserver(forInterval: time,
                                                            queue: .main) {
            [weak self] time in
            // update player transport UI
            guard let duration = self?.model?.duration,duration > 0 else {
                return
            }
            
            let p = time.seconds/duration.double
            
            self?.progress_view.progress = Float(p)
            
        }
    }
    
    private func remove_periodic_time_observer() {
        if let time_observer_token = time_observer_token {
            player?.removeTimeObserver(time_observer_token)
            self.time_observer_token = nil
        }
    }
    
}




